package com.hmz.backend.component;

import cn.hutool.core.bean.BeanUtil;
import com.hmz.backend.entity.Message;
import com.hmz.backend.mapper.MessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 每天固定时间将Redis中的数据持久化在Mysql
 */
@Component
public class MyTimer {
    @Autowired
    private RedisTemplate redisTemplate; //操作redis
    @Autowired
    private MessageMapper messageMapper; //信息相关的数据库操作
    //将redis中的数据插入到Mysql中
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点执行一次
//    @PostConstruct
    public void insertDB(){
        Set<String> keys = redisTemplate.keys("message*"); //获取以message开头的key值
        for (String key:keys) { //遍历每一个key
            //拿到对应key下的消息list
            List<HashMap> list = redisTemplate.opsForList().range(key, 0, -1);
            List<Message> messageList = new ArrayList<>();
            for(HashMap message : list) messageList.add(BeanUtil.fillBeanWithMap(message,new Message(),false)); //将list中的每个item转成message
            long stime = System.currentTimeMillis();  //当前时间戳
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //日期格式化
            //流式映射将每个message都转成相应格式的字符串
            Stream<String> stringStream = messageList.stream().map(item -> "(NULL," + item.getSenderId() + "," + item.getReceiverId() + ",'" + item.getContent() + "'," + item.getType() + ",'" + dateFormat.format(item.getCreateTime())+"'),");
            //将流中的每个字符串进行拼接
            String sql = stringStream.collect(Collectors.joining());
            //去掉最后一个逗号，将其替换为分号
            String insertSql = sql.substring(0,sql.lastIndexOf(","))+";";
            //执行sql
            messageMapper.insertMessageList(Integer.parseInt(key),insertSql);
            redisTemplate.delete(key);//从redis中删除key值
            long etime = System.currentTimeMillis(); //执行完的时间戳
            System.out.printf("执行时长：%d 毫秒.", (etime - stime)); //统计时间
        }
        System.out.println("数据转移完成");
    }
}
/**
 * 批量插入聊天室实体
 */
//    @PostConstruct
//    void test(){
////        List<ChatRoom> chatRoomList = new ArrayList<>();
////        for(int i=0;i<1000;i++){
////            ChatRoom chatRoom = new ChatRoom();
////            chatRoom.setChatRoomName("testChatRoom"+i);
////            chatRoom.setTime(new Date());
////            chatRoom.setNum(1);
////            chatRoomList.add(chatRoom);
////        }
////        chatRoomMapper.insertList(BeanToSQL.formatForSqlInsertList(chatRoomList));
//    }
/**
 * 批量插入加入聊天室关系
 */
//    @PostConstruct
//    void test(){
//        String temps = "(null,1,";
//        String sql = "";
//        for (int i=2072;i<1000+2072;i++){
//            sql+=temps+i+")";
//            if(i != 999+2072) sql+=",";
//            else sql+=";";
//        }
//        chatRoomMapper.insertPersonList(sql);
//        System.out.println("插入完成");
//    }
//
/**
 * 批量建表
 */
//    @PostConstruct
//    void test(){
//        for (int i=2072;i<1000+2072;i++){
//            chatRoomMapper.createMessageTable(i);
//            System.out.println("建表完成");
//        }
//    }
/**
 * 批量插入所属关系
 *
 */
//    @PostConstruct
//    void test(){
//        for(int i=2072;i<1000+2072;i++){
//            String sql ="";
//            for(int j=10;j<510;j++){
//                String temps = "(null,";
//                temps += j+",";
//                temps += i+")";
//                if(j!=509) temps+=",";
//                else temps += ";";
//                sql+= temps;
//            }
//            chatRoomMapper.insertPersonList(sql);
//            System.out.println("插入完成");
//        }
//    }
/**
 * 随机生成消息实体插入对应的消息表中
 */
//    @PostConstruct
//    void test(){
//        Random random = new Random();
//        for(int i= 2260;i<1000+2072;i++){
//            List<Message> messageList = new ArrayList<>();
//            long stime = System.currentTimeMillis();
//            for(int j=0;j<1e4;j++){
//                Message message = new Message();
//                message.setType(0);
//                message.setCreateTime(new Date());
//                message.setContent("testMessage"+j);
//                message.setReceiverId(i);
//                message.setSenderId(random.nextInt(10,510));
//                messageList.add(message);
//            }
//            messageMapper.insertMessageList(i,BeanToSQL.formatForSqlInsertList(messageList));
//            long etime = System.currentTimeMillis();
//            System.out.printf("执行时长：%d 毫秒.", (etime - stime));
//            System.out.println("插入完成："+i);
//        }
//    }